package com.easylinkin.linkappapi.config.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.config.entity.SysDict;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.config.service.SysDictItemService;
import com.easylinkin.linkappapi.config.service.SysDictService;
import com.easylinkin.linkappapi.config.vo.SysDictItemQueryRequestVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;


 /**
 * 数据字典/数据字典详情
 */
@Slf4j
@RequestMapping("sys/dict/item")
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysDictItemController {

     final String moduleName = "系统管理-数据字典明细";

    private final SysDictItemService service;
    
    private final SysDictService dictService;
    

    /**
     * 数据字典分类明细列表
     *
     * @param requestVo 数据字典分类明细查询对象
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.GET)
    public RestMessage page(@Validated RequestModel<SysDictItemQueryRequestVo> requestVo) {
        IPage page = service.page(requestVo.getPage(), requestVo.getCustomQueryParams().getQueryWrapper());
        return RestBuilders.successBuilder(page).build();
    }

    /**
     * 新增数据字典分类明细
     *
     * @param requestVo 数据字典分类明细对象
     */
    @RequestMapping(method = RequestMethod.POST)
    public RestMessage create(@RequestBody @Validated SysDictItemQueryRequestVo requestVo) {
        // 校验Value是否重复
        SysDictItem one = service.getOne(new LambdaQueryWrapper<SysDictItem>()
                .eq(SysDictItem::getItemValue, requestVo.getItemValue())
                .eq(SysDictItem::getDictId, requestVo.getDictId()));
        if (one!=null) {
            throw new BusinessException("数据字典明细项值已存在");
        }
        SysDictItem entity = requestVo.toEntity();
        SysDict dict = dictService.getById(entity.getDictId());
        if (dict == null) {
          throw new BusinessException("数据字典分类不存在");
        }
        entity.setIsSync(false);
        service.save(entity);
        return RestBuilders.successBuilder(entity).build();
    }

    /**
     * 数据字典分类明细详情
     *
     * @param id 数据字典分类明细Id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public RestMessage get(@PathVariable Long id) {
        return RestBuilders.successBuilder(service.getById(id)).build();
    }

    /**
     * 更新数据字典分类明细
     *
     * @param id 数据字典分类明细Id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public RestMessage update(@PathVariable Long id, @RequestBody @Validated SysDictItemQueryRequestVo requestVo) {
        SysDictItem one = service.getOne(new LambdaQueryWrapper<SysDictItem>()
                .eq(SysDictItem::getItemValue, requestVo.getItemValue())
                .eq(SysDictItem::getDictId, requestVo.getDictId())
                .ne(SysDictItem::getId, id));
        if (one!=null) {
            throw new BusinessException("数据字典明细项值已存在");
        }
        SysDictItem entity = requestVo.toEntity();
        entity.setIsSync(false);
        entity.setId(id);
        service.updateById(entity);
        SysDict dict = dictService.getById(entity.getDictId());
        if (dict == null) {
          throw new BusinessException("数据字典分类不存在");
        }
        return RestBuilders.successBuilder(dict).build();
    }

    /**
     * 删除数据字典分类明细
     *
     * @param id 数据字典分类明细Id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public RestMessage delete(@PathVariable Long id) {
        SysDictItem item = service.getById(id);
        if (item != null) {
          SysDict dict = dictService.getById(item.getDictId());
        }
        service.removeById(id);
        return RestBuilders.successBuilder().build();
    }
//    /**
//     * 同步缓存
//     * @return
//     */
//    @PostMapping("/sync-cache")
//    public RestResponse<?> syncCache() {
//      poolTaskExecutor.execute(() -> {
//          cacheService.doCache();
//      });
//      // 模拟耗时
//      try {
//        TimeUnit.SECONDS.sleep(5);
//      } catch (InterruptedException e) {
//        log.error(e.getMessage(), e);
//      }
//      return RestResponse.success();
//    }

}